<template>
	<view class="container">
		<!-- 搜索栏 -->
		<view class="search-box">
			<uni-search-bar placeholder="搜索课程、学生或内容" radius="30" bgColor="#fff" @confirm="onSearch"></uni-search-bar>
		</view>
		<!-- 功能导航 -->
		<uni-grid :column="4" :highlight="false" :show-border="false">
			<uni-grid-item>
				<view class="grid-item" @click="opencreatePopup">
					<uni-icons type="plus-filled" size="32" color="#5B89F7"></uni-icons>
					<text>新建课程</text>
				</view>
			</uni-grid-item>
			<uni-grid-item>
				<view class="grid-item">
					<uni-icons type="calendar" size="32" color="#FF9A2E"></uni-icons>
					<text>课程表</text>
				</view>
			</uni-grid-item>
			<uni-grid-item>
				<view class="grid-item">
					<uni-icons type="staff-filled" size="32" color="#00B894"></uni-icons>
					<text>学生管理</text>
				</view>
			</uni-grid-item>
			<uni-grid-item>
				<view class="grid-item">
					<uni-icons type="download-filled" size="32" color="#F54E4E"></uni-icons>
					<text>资源库</text>
				</view>
			</uni-grid-item>
		</uni-grid>
		<!-- 最近课程 -->
		<view class="section">
			<view class="section-header">
				<text class="section-title">今日课程</text>
			</view>
			<scroll-view scroll-x class="course-scroll" style="height: 500rpx;">
				<view class="course-content">
					<uni-card v-for="(course, index) in Todaycourse" :key="index" class="course-card"
						style="width: 600rpx;" :title="course.courseName"
						:extra="`状态：${course.status === 'active' ? '进行中' : '已归档'}`"
						:style="{ width: cardWidth + 'px' }">

						<uni-list>
							<uni-list-item title="授课教师" :rightText="course.teacherUsername" show-arrow="false" />
							<uni-list-item title="课程时间"
								:rightText="`${formatDate(course.startTime)} 至 ${formatDate(course.endTime)}`"
								show-arrow="false" />
							<uni-list-item title="上课日期" :rightText="formatOpenDays(course.openday)"
								show-arrow="false" />
						</uni-list>
						<view class="student-section">
							<uni-icons type="person" size="16" color="#666"></uni-icons>
							<text class="student-count">{{ course.students.length }}名学生</text>
						</view>

					</uni-card>
				</view>
			</scroll-view>
		</view>
		<!-- 待办事项 -->
		<view class="section">
			<view class="section-header">
				<text class="section-title">今日待办</text>
				<text class="more">全部</text>
			</view>
			<uni-list>
				<uni-list-item v-for="(task, index) in tasks" :key="index" :title="task.title"
					:note="`截止时间：${task.deadline}`" show-extra-icon
					:extra-icon="{ type: 'circle-filled', color: task.done ? '#00B894' : '#eee' }" />
			</uni-list>
		</view>
		<!-- 创建课程弹窗 -->
		<uni-popup ref="createPopup" type="bottom" :mask-click="false">
			<view class="create-course-popup">
				<view class="popup-header">
					<text class="title">创建新课程</text>
					<view class="close-btn" @click="closePopup">×</view>
				</view>
				<form @submit.prevent="handleSubmit">
					<view class="form-item">
						<text class="label">课程名称：</text>
						<input v-model="formData.courseName" placeholder="请输入课程名称" required />
					</view>
					<view class="form-item">
						<text class="label">开始时间：</text>
						<uni-datetime-picker type="date" :value="formData.startTime"
							@change="(e) => changeTime('start', e)" />
					</view>
					<view class="form-item">
						<text class="label">结束时间：</text>
						<uni-datetime-picker type="date" :value="formData.endTime"
							@change="(e) => changeTime('end', e)" />
					</view>
					<view class="form-item">
						<text class="label">课程状态：</text>
						<picker :range="statusOptions" @change="handleStatusChange"
							:value="statusOptions.indexOf(formData.status)">
							<view class="picker-item">
								{{ formData.status || '请选择状态' }}
							</view>
						</picker>
					</view>
					<view class="form-item">
						<text class="label">课程描述：</text>
						<textarea v-model="formData.description" placeholder="请输入课程描述" maxlength="200" />
					</view>
					<view class="button-group">
						<button form-type="submit" class="submit-btn">立即创建</button>
						<button type="default" class="cancel-btn" @click="closePopup">取消</button>
					</view>
				</form>
			</view>
		</uni-popup>
	</view>
</template>

<script>
import {
	createCourse, getTeacherCourse
} from '@/request/teacherCourse'
export default {
	onLoad() {
		this.userInfo = uni.getStorageSync('userInfo')
	},
	data() {
		// 先获取用户信息
		const userInfo = uni.getStorageSync('userInfo') || {}
		return {
			courses: [], // 初始化数据
			tasks: [],   // 初始化数据
			formData: {
				courseName: '',
				teacherId: userInfo.userId,
				startTime: '',
				endTime: '',
				status: 'active',
				description: ''
			},
			Todaycourse: [],
			userInfo: userInfo,
			statusOptions: ['active', 'archived'],
			cardWidth: 400 // 根据设计稿调整
		}
	},
	mounted() {
		this.userInfo = uni.getStorageSync('userInfo')
		this.getTodaycourse()
		console.log(this.userInfo, 'userInfo', this.formData, 'formData');
	},
	methods: {
		// 统一处理时间变更
		changeTime(type, e) {
			if (type === 'start') {
				this.formData.startTime = e.detail.value
			} else {
				this.formData.endTime = e.detail.value
			}
		},
		// 日期格式化
		formatDate(dateString) {
			if (!dateString) return ''
			const date = new Date(dateString)
			return `${date.getFullYear()}年${date.getMonth() + 1}月${date.getDate()}日`
		},
		// 周几格式化
		formatOpenDays(days) {
			const dayMap = {
				'MONDAY': '周一',
				'TUESDAY': '周二',
				'WEDNESDAY': '周三',
				'THURSDAY': '周四',
				'FRIDAY': '周五',
				'SATURDAY': '周六',
				'SUNDAY': '周日'
			}
			return days.split(',')
				.map(day => dayMap[day.trim()] || day)
				.join('、')
		},
		getTodaycourse() {
			getTeacherCourse({
				teacherId: this.userInfo.userId
			}).then(res => {
				this.Todaycourse = res.data
				console.log(this.Todaycourse, 'Todaycourse');
			})
		},
		// 状态选择
		handleStatusChange(e) {
			this.formData.status = this.statusOptions[e.detail.value]
		},
		// 表单提交
		async handleSubmit() {
			if (!this.validateForm()) return
			try {
				await createCourse(this.formData)
				uni.showToast({ title: '创建成功', icon: 'success' })
				this.closePopup()
			} catch (error) {
				uni.showToast({
					title: error.message || '创建失败',
					icon: 'none'
				})
			}
		},
		// 表单验证
		validateForm() {
			const requiredFields = [
				{ field: 'courseName', message: '请输入课程名称' },
				{ field: 'startTime', message: '请选择开始时间' },
				{ field: 'endTime', message: '请选择结束时间' }
			]
			for (const { field, message } of requiredFields) {
				if (!this.formData[field]?.trim()) {
					uni.showToast({ title: message, icon: 'none' })
					return false
				}
			}
			if (new Date(this.formData.startTime) >= new Date(this.formData.endTime)) {
				uni.showToast({ title: '结束时间必须晚于开始时间', icon: 'none' })
				return false
			}
			return true
		},
		// 打开弹窗
		opencreatePopup() {
			this.$refs.createPopup.open()
		},
		// 关闭弹窗
		closePopup() {
			this.$refs.createPopup.close()
			this.resetForm()
		},
		resetForm() {
			this.formData = {
				courseName: '',
				teacherId: this.userInfo.userId || '', // 动态获取最新 userInfo
				startTime: '',
				endTime: '',
				status: 'active', // 强制重置为默认值
				description: ''
			}
		},
		onSearch() {
			// 搜索功能实现
		}
	},
}
</script>

<style lang="scss">
.container {
	background: #f5f6fa;
	min-height: 100vh;
	padding: 20rpx;
}

.header {
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding: 30rpx;
	background: linear-gradient(135deg, #5B89F7, #6F5BFF);
	border-radius: 20rpx;
	margin-bottom: 30rpx;

	.user-info {
		display: flex;
		align-items: center;
		gap: 20rpx;

		.username {
			color: #fff;
			font-size: 32rpx;
			font-weight: 500;
		}
	}
}

.search-box {
	margin: 20rpx 0;
}

.grid-item {
	display: flex;
	flex-direction: column;
	align-items: center;
	padding: 30rpx 0;

	text {
		font-size: 24rpx;
		color: #666;
		margin-top: 15rpx;
	}
}

.section {
	background: #fff;
	border-radius: 20rpx;
	padding: 30rpx;
	margin-top: 30rpx;

	&-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 30rpx;
	}

	&-title {
		font-size: 32rpx;
		font-weight: 600;
		color: #333;
	}

	.more {
		color: #999;
		font-size: 26rpx;
	}
}

/* 修改样式部分 */
.course-scroll {
  width: 100%;
  white-space: nowrap;
  
  /* 隐藏原生滚动条 */
  ::-webkit-scrollbar {
    display: none;
    width: 0;
    height: 0;
    color: transparent;
  }

  .scroll-content {
    display: inline-block;
    padding: 20rpx 0;
  }

  .course-card {
    display: inline-block;
    margin-right: 30rpx;
    vertical-align: top;
    
    &:last-child {
      margin-right: 0;
    }
  }
}

.course-content {
	.uni-list-item {
		padding: 16rpx 0;

		::v-deep .uni-list-item__container {
			padding: 0;
		}
	}
}

.student-section {
	display: flex;
	align-items: center;
	margin-top: 20rpx;
	padding: 16rpx;
	background-color: #f8f9fa;
	border-radius: 8rpx;

	.student-count {
		margin-left: 10rpx;
		font-size: 24rpx;
		color: #666;
	}
}

/* 添加弹窗样式 */
.create-course-popup {
	background: #fff;
	border-top-left-radius: 24rpx;
	border-top-right-radius: 24rpx;
	padding: 40rpx;

	.popup-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 40rpx;

		.title {
			font-size: 36rpx;
			font-weight: 600;
			color: #333;
		}

		.close-btn {
			font-size: 32rpx;
			color: #999;
			cursor: pointer;
		}
	}

	.form-item {
		margin-bottom: 32rpx;

		input,
		textarea,
		.uni-datetime-picker {
			width: 100%;
			padding: 24rpx;
			border: 1px solid #e0e0e0;
			border-radius: 12rpx;
			font-size: 28rpx;
			background: #f8f9fa;
		}

		.picker-item {
			padding: 24rpx;
			border: 1px solid #e0e0e0;
			border-radius: 12rpx;
		}
	}

	.button-group {
		display: flex;
		gap: 20rpx;
		margin-top: 48rpx;

		button {
			flex: 1;
			height: 88rpx;
			line-height: 88rpx;
			font-size: 30rpx;
			transition: opacity 0.3s;

			&:active {
				opacity: 0.8;
			}
		}

		.submit-btn {
			background: #5B89F7;
			color: white;
		}

		.cancel-btn {
			background: #f5f5f5;
			color: #666;
		}
	}
}

.course-card {
	transition: transform 0.3s ease;

	&:hover {
		transform: scale(1.02);
		box-shadow: 0 8rpx 24rpx rgba(0, 0, 0, 0.15);
	}

	&:active {
		transform: scale(0.98);
	}
}
</style>